package com.zhuhjay.controller;

import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.zhuhjay.model.domain.HttpResult;
import com.zhuhjay.model.dto.ResetPwdDto;
import com.zhuhjay.model.dto.UserLoginDto;
import com.zhuhjay.service.UserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import static com.zhuhjay.constant.CacheConstant.KAPTCHA_CACHE_PREFIX;

/**
 * @author ZhuHJay
 * @date 2023/4/24 22:21
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private Cache<String, String> codeCache;

    @PostMapping("login")
    public HttpResult<?> login(@RequestBody @Validated UserLoginDto userDto, HttpSession session){
        String sessionId = session.getId();
        String code = codeCache.getIfPresent(KAPTCHA_CACHE_PREFIX + sessionId);
        if (StrUtil.isBlank(code)) {
            return HttpResult.fail("验证码已过期");
        }
        if (!code.equalsIgnoreCase(userDto.getValcode())) {
            return HttpResult.fail("验证码错误");
        }
        userService.login(userDto);
        return HttpResult.ok();
    }

    @PostMapping("reset/pwd.auth")
    public HttpResult<?> resetPwd(@RequestBody @Validated ResetPwdDto resetPwdDto){
        userService.resetPwd(resetPwdDto);
        return HttpResult.ok();
    }

}
